package com.glasses.business.fragment;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.glasses.business.R;
import com.glasses.business.activity.WebDetailActiviy;
import com.glasses.business.adapter.CheckLightAdapter;
import com.glasses.business.adapter.InfoAdapter;
import com.glasses.business.appliction.MyApplication;
import com.glasses.business.base.MyBaseAdapter;
import com.glasses.business.entity.CheckList;
import com.glasses.business.entity.NewsList;
import com.glasses.business.fmanager.BaseFragment;
import com.glasses.business.http.NetUtils;
import com.glasses.business.utils.Tools;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import net.neiquan.applibrary.wight.RefreshLayout;
import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import org.haitao.common.utils.KeyBoardUtils;
import org.haitao.common.utils.ToastUtil;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Author：邓勇军
 * English Name：Deng,The Sky Fucker!
 * Email：dandycoder@126.com
 * Date：2017/3/9
 * Version：1.0
 */

public class SearchFragment_ extends BaseFragment implements RefreshLayout.RetryListener, XRecyclerView.LoadingListener {
    @InjectView(R.id.searchBack)
    ImageView searchBack;
    @InjectView(R.id.searchEtv)
    EditText searchEtv;
    @InjectView(R.id.searchCancel)
    ImageView searchCancel;
    @InjectView(R.id.recyclerview)
    XRecyclerView mRecyclerview;
    @InjectView(R.id.refesh_ly)
    RefreshLayout mRefeshLy;
    private InfoAdapter infoAdapter;
    private int pageNum = 0;
    private int PageSize = 10;
    @Override
    public int getRootViewId() {
        return R.layout.fragment_search;
    }

    @Override
    public void setViews() {
        infoAdapter = new InfoAdapter(getActivity(), null);
        mRecyclerview.setAdapter(infoAdapter);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1,
                StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setOrientation(StaggeredGridLayoutManager.VERTICAL);
        mRecyclerview.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerview.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerview.setArrowImageView(R.mipmap.iconfont_downgrey);
        mRecyclerview.setHasFixedSize(true);
        mRecyclerview.setLayoutManager(layoutManager);
        mRefeshLy.setRetryListener(this);

        mRecyclerview.setLoadingListener(this);
        mRecyclerview.setLoadingMoreEnabled(false);
        mRecyclerview.setPullRefreshEnabled(true);

        infoAdapter.setOnItemClickListener(new MyBaseAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, List data, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("title", "资讯详情");
                NewsList newsList = (NewsList) data.get(position);
                bundle.putString("url", newsList.getUrl());
                Intent intent = new Intent(getActivity(), WebDetailActiviy.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    public void initData() {
        searchEtv.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH){
                    KeyBoardUtils.hideSoftInput(searchEtv);
                    onRefresh();
                    return true;
                }
                return false;
            }
        });
        loadDatas(true);
    }

    @Override
    public boolean mainTabShow() {
        return false;
    }

    private void loadDatas(final boolean isRefush) {
        String keyWord = searchEtv.getText().toString();
        Location location = MyApplication.getInstance().location;
        if (location != null) {
            Tools.showDialog(getActivity());
            NetUtils.getInstance().newList( pageNum, PageSize, keyWord,new NetCallBack() {
                @Override
                public void onSuccess(String response, String mssage, ResultModel model) {
                    Tools.dismissWaitDialog();
                    ToastUtil.shortShowToast(mssage);
                    mRecyclerview.loadMoreComplete();
                    mRecyclerview.refreshComplete();
                    mRefeshLy.hideAll();
                    List<NewsList> list = (List<NewsList>) model.getModelList();
                    if (isRefush) {
                        infoAdapter.clear();
                    }
                    infoAdapter.append(list);
                    if (list == null || list.size() < 10) {
                        if (isRefush && (list == null || list.size() == 0)) {
//                        mRefeshLy.showEmptyView();
                            mRefeshLy.showFailView();
                        }
                        mRecyclerview.setLoadingMoreEnabled(false);
                    } else {
                        mRecyclerview.setLoadingMoreEnabled(true);
                    }
                }

                @Override
                public void onFail(boolean dataError, int errorCode, String mssage) {
                    Tools.dismissWaitDialog();
                    ToastUtil.shortShowToast(mssage);
                    //                mRefeshLy.hideAll();
                    mRefeshLy.showFailView();
                    mRecyclerview.loadMoreComplete();
                    mRecyclerview.refreshComplete();
                }
            }, NewsList.class);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @OnClick({R.id.searchBack, R.id.searchCancel})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.searchBack:
                MyApplication.getInstance().manager.onBackPressed();
                break;
            case R.id.searchCancel:
                searchEtv.setText("");
                break;
        }
    }

    @Override
    public void onRetryClick() {
        pageNum=0;
        loadDatas(true);
    }

    @Override
    public void onRefresh() {
        pageNum=0;
        loadDatas(true);
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        loadDatas(false);
    }
}
